package com.xiaoxu.rental.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xiaoxu.rental.config.OSSConfig;
import com.xiaoxu.rental.service.OssService;
import com.xiaoxu.rental.util.FileUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Title: OssServiceImpl
 * @Author Mr.Xu
 * @Package com.xiaoxu.rental.service.impl
 * @Date 2024/7/30 16:10
 * @description:
 */
@Service
@Transactional
public class OssServiceImpl implements OssService {
    @Resource
    private OSSConfig ossConfig;

    @Override
    public String upload(MultipartFile file) {


        //要上传文件的原始名
        String originalFilename = file.getOriginalFilename();
        //获取新的文件名
        String fileName = FileUtils.getFileName(originalFilename);
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );
        try {
            //完成上传处理
            ossClient.putObject(ossConfig.getBucketName(), fileName,
                    file.getInputStream());
            return "https://" + ossConfig.getBucketName() + "." +
                    ossConfig.getEndpoint() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("上传失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public boolean delete(String url) {
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );
        String host = "https://" + ossConfig.getBucketName() + "." +
                ossConfig.getEndpoint() + "/";
        String objectName = StrUtil.removePrefix(url, host);//avatar.png
        try {
            ossClient.deleteObject(ossConfig.getBucketName(), objectName);
            return true;
        } catch (Exception e) {
            throw new RuntimeException("删除失败");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
